package com.king.platform.config;

import feign.Logger.Level;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class FeignConfig {

  private static final Logger log = LoggerFactory.getLogger(FeignConfig.class);


  @Bean
  Level feignLevel() {
    return Level.FULL;
  }

  @Bean
  public HttpClient httpClient() {
    log.info("====== Apache httpclient FeignClient... ======");
    org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(10000);
    requestConfigBuilder.setConnectTimeout(60000);
    requestConfigBuilder.setSocketTimeout(120000);
    RequestConfig defaultRequestConfig = requestConfigBuilder.build();
    final PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30L, TimeUnit.SECONDS);
    pollingConnectionManager.setMaxTotal(2000);
    pollingConnectionManager.setDefaultMaxPerRoute(1000);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
    HttpClient client = httpClientBuilder.build();
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      public void run() {
        pollingConnectionManager.closeExpiredConnections();
        pollingConnectionManager.closeIdleConnections(10L, TimeUnit.SECONDS);
      }
    }, 20000L, 20000L);
    log.info("====== Apache httpclient 初始化连接池完毕 ======");
    return client;
  }

}
